import { Toast } from "vant";
export default {
  namespaced: true,
  state() {
    return {
      songList: [], // 歌单列表
      isFullScreen: true, // 大小屏切换
      curSongIdx: -1, // 当前播放的歌曲下标
      likes: JSON.parse(localStorage.getItem("likes")) || [], // 喜欢默认为空
    };
  },
  mutations: {
    toggleScreen(state, screenState) {
      // 切换大小屏
      state.isFullScreen = screenState;
    },
    addSongList(state, list) {
      // 添加歌单
      state.songList = list;
    },
    changeCurSongIdx(state, idx) {
      // 切换当前播放歌曲的下标
      state.curSongIdx = idx;
    },
    addLikesList(state, likeSongData) {
      const list = state.likes;
      // 判断歌在不在 如果在取消喜欢
      let isExist = -1;
      for (let index = 0; index < list.length; index++) {
        if (likeSongData.mid === list[index].mid) {
          isExist = index;
        }
      }
      if (isExist === -1) {
        list.push(likeSongData);
        Toast({
          message: "收藏成功啦",
          icon: "like-o",
        });
      } else {
        list.splice(isExist, 1);
        Toast("你取消了收藏");
      }
      // 存入state
      state.likes = list;
      // 存入vuex
      localStorage.setItem("likes", JSON.stringify(list));
    },
    // 随机取整 播放
    randomPlay(state) {
      const max = state.songList.length;
      state.curSongIdx = parseInt(Math.random() * max);
    },
  },
  getters: {
    curSong(state) {
      // 根据歌单列表 和 歌曲播放下标获取对应的播放歌曲
      return state.songList[state.curSongIdx] || {};
    },
    isLikeState(state) {
      const { likes, songList, curSongIdx } = state; // 喜欢的列表
      const curSong = songList[curSongIdx];
      // console.log('xxxxx',curSong,songList)
      for (let index = 0; index < likes.length; index++) {
        if (curSong && likes[index].mid === curSong.mid) return true;
      }
      return false;
    },
  },
  actions: {
    prevOrNext(ctx, payload) {
      console.log("prevOrNext", ctx, payload);
      let { curSongIdx, songList } = ctx.state;
      let max = songList.length;
      if (payload === "next") {
        // 下一首
        curSongIdx += 1;
        if (curSongIdx >= max) {
          curSongIdx = 0;
        }
      } else {
        // 前一首
        curSongIdx -= 1;
        if (curSongIdx <= -1) {
          curSongIdx = max - 1;
        }
      }

      ctx.commit("changeCurSongIdx", curSongIdx);
    },
  },
};
